// MongoDB初始化脚本
// 创建时间: 2024年

// 切换到目标数据库
db = db.getSiblingDB('zhunong_ai_platform');

// 创建数据库用户
db.createUser({
  user: 'zhunong',
  pwd: 'zhunong123',
  roles: [
    { role: 'readWrite', db: 'zhunong_ai_platform' }
  ]
});

// 创建集合和索引
print('开始创建集合和索引...');

// 1. 用户集合
db.createCollection('users', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['username', 'email', 'password_hash'],
      properties: {
        username: {
          bsonType: 'string',
          minLength: 3,
          maxLength: 50,
          pattern: '^[a-zA-Z0-9_]+$'
        },
        email: {
          bsonType: 'string',
          pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'
        },
        phone: {
          bsonType: 'string',
          pattern: '^1[3-9]\\d{9}$'
        },
        password_hash: { bsonType: 'string' },
        real_name: { bsonType: 'string' },
        avatar: { bsonType: 'string' },
        gender: { enum: ['male', 'female', 'other'] },
        birth_date: { bsonType: 'date' },
        address: { bsonType: 'string' },
        is_verified: { bsonType: 'bool' },
        status: { enum: ['active', 'inactive', 'banned'] },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 用户集合索引
db.users.createIndex({ username: 1 }, { unique: true });
db.users.createIndex({ email: 1 }, { unique: true });
db.users.createIndex({ phone: 1 }, { sparse: true });
db.users.createIndex({ status: 1 });
db.users.createIndex({ created_at: -1 });

// 2. 农户集合
db.createCollection('farmers', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['user_id', 'farm_name', 'farm_address'],
      properties: {
        user_id: { bsonType: 'objectId' },
        farm_name: { bsonType: 'string' },
        farm_address: { bsonType: 'string' },
        farm_size: { bsonType: 'double' },
        farm_type: { enum: ['individual', 'cooperative', 'company'] },
        certification: { bsonType: 'string' },
        description: { bsonType: 'string' },
        contact_person: { bsonType: 'string' },
        contact_phone: { bsonType: 'string' },
        business_license: { bsonType: 'string' },
        location: {
          bsonType: 'object',
          properties: {
            type: { enum: ['Point'] },
            coordinates: {
              bsonType: 'array',
              items: { bsonType: 'double' }
            }
          }
        },
        is_verified: { bsonType: 'bool' },
        verification_date: { bsonType: 'date' },
        status: { enum: ['pending', 'approved', 'rejected', 'suspended'] },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 农户集合索引
db.farmers.createIndex({ user_id: 1 }, { unique: true });
db.farmers.createIndex({ farm_name: 1 });
db.farmers.createIndex({ status: 1 });
db.farmers.createIndex({ location: '2dsphere' });
db.farmers.createIndex({ created_at: -1 });

// 3. 商品分类集合
db.createCollection('categories', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['name'],
      properties: {
        name: { bsonType: 'string' },
        description: { bsonType: 'string' },
        icon: { bsonType: 'string' },
        parent_id: { bsonType: 'objectId' },
        sort_order: { bsonType: 'int' },
        is_active: { bsonType: 'bool' },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 分类集合索引
db.categories.createIndex({ name: 1 }, { unique: true });
db.categories.createIndex({ parent_id: 1 });
db.categories.createIndex({ sort_order: 1 });
db.categories.createIndex({ is_active: 1 });

// 4. 商品集合
db.createCollection('products', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['farmer_id', 'category_id', 'name', 'price', 'unit'],
      properties: {
        farmer_id: { bsonType: 'objectId' },
        category_id: { bsonType: 'objectId' },
        name: { bsonType: 'string' },
        description: { bsonType: 'string' },
        price: { bsonType: 'double' },
        original_price: { bsonType: 'double' },
        stock_quantity: { bsonType: 'int' },
        unit: { bsonType: 'string' },
        min_order_quantity: { bsonType: 'int' },
        images: { bsonType: 'array' },
        tags: { bsonType: 'array' },
        harvest_date: { bsonType: 'date' },
        expiry_date: { bsonType: 'date' },
        origin_place: { bsonType: 'string' },
        location: {
          bsonType: 'object',
          properties: {
            type: { enum: ['Point'] },
            coordinates: {
              bsonType: 'array',
              items: { bsonType: 'double' }
            }
          }
        },
        quality_grade: { enum: ['A', 'B', 'C'] },
        is_organic: { bsonType: 'bool' },
        is_featured: { bsonType: 'bool' },
        status: { enum: ['draft', 'active', 'inactive', 'sold_out'] },
        view_count: { bsonType: 'int' },
        sale_count: { bsonType: 'int' },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 商品集合索引
db.products.createIndex({ farmer_id: 1 });
db.products.createIndex({ category_id: 1 });
db.products.createIndex({ status: 1 });
db.products.createIndex({ price: 1 });
db.products.createIndex({ is_featured: 1 });
db.products.createIndex({ location: '2dsphere' });
db.products.createIndex({ name: 'text', description: 'text' });
db.products.createIndex({ created_at: -1 });

// 5. 订单集合
db.createCollection('orders', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['order_no', 'user_id', 'farmer_id', 'total_amount', 'final_amount'],
      properties: {
        order_no: { bsonType: 'string' },
        user_id: { bsonType: 'objectId' },
        farmer_id: { bsonType: 'objectId' },
        total_amount: { bsonType: 'double' },
        discount_amount: { bsonType: 'double' },
        final_amount: { bsonType: 'double' },
        shipping_fee: { bsonType: 'double' },
        shipping_address: { bsonType: 'string' },
        shipping_contact: { bsonType: 'string' },
        shipping_phone: { bsonType: 'string' },
        payment_method: { enum: ['wechat', 'alipay', 'bank'] },
        payment_status: { enum: ['pending', 'paid', 'failed', 'refunded'] },
        order_status: { enum: ['pending', 'confirmed', 'shipped', 'delivered', 'cancelled', 'refunded'] },
        delivery_company: { bsonType: 'string' },
        tracking_number: { bsonType: 'string' },
        estimated_delivery: { bsonType: 'date' },
        actual_delivery_date: { bsonType: 'date' },
        notes: { bsonType: 'string' },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 订单集合索引
db.orders.createIndex({ order_no: 1 }, { unique: true });
db.orders.createIndex({ user_id: 1 });
db.orders.createIndex({ farmer_id: 1 });
db.orders.createIndex({ order_status: 1 });
db.orders.createIndex({ payment_status: 1 });
db.orders.createIndex({ created_at: -1 });

// 6. 订单详情集合
db.createCollection('order_items', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['order_id', 'product_id', 'product_name', 'unit_price', 'quantity', 'total_price'],
      properties: {
        order_id: { bsonType: 'objectId' },
        product_id: { bsonType: 'objectId' },
        product_name: { bsonType: 'string' },
        product_image: { bsonType: 'string' },
        unit_price: { bsonType: 'double' },
        quantity: { bsonType: 'int' },
        total_price: { bsonType: 'double' },
        created_at: { bsonType: 'date' }
      }
    }
  }
});

// 订单详情集合索引
db.order_items.createIndex({ order_id: 1 });
db.order_items.createIndex({ product_id: 1 });
db.order_items.createIndex({ created_at: -1 });

// 7. 购物车集合
db.createCollection('cart_items', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['user_id', 'product_id', 'quantity'],
      properties: {
        user_id: { bsonType: 'objectId' },
        product_id: { bsonType: 'objectId' },
        quantity: { bsonType: 'int' },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 购物车集合索引
db.cart_items.createIndex({ user_id: 1 });
db.cart_items.createIndex({ product_id: 1 });
db.cart_items.createIndex({ user_id: 1, product_id: 1 }, { unique: true });
db.cart_items.createIndex({ created_at: -1 });

// 8. 评价集合
db.createCollection('reviews', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['order_id', 'user_id', 'product_id', 'farmer_id', 'rating'],
      properties: {
        order_id: { bsonType: 'objectId' },
        user_id: { bsonType: 'objectId' },
        product_id: { bsonType: 'objectId' },
        farmer_id: { bsonType: 'objectId' },
        rating: { bsonType: 'int', minimum: 1, maximum: 5 },
        content: { bsonType: 'string' },
        images: { bsonType: 'array' },
        is_anonymous: { bsonType: 'bool' },
        status: { enum: ['pending', 'approved', 'rejected'] },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 评价集合索引
db.reviews.createIndex({ order_id: 1 });
db.reviews.createIndex({ user_id: 1 });
db.reviews.createIndex({ product_id: 1 });
db.reviews.createIndex({ farmer_id: 1 });
db.reviews.createIndex({ rating: 1 });
db.reviews.createIndex({ status: 1 });
db.reviews.createIndex({ created_at: -1 });

// 9. AI种植建议集合
db.createCollection('ai_planting_advice', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['farmer_id', 'crop_type', 'title', 'content'],
      properties: {
        farmer_id: { bsonType: 'objectId' },
        crop_type: { bsonType: 'string' },
        advice_type: { enum: ['planting', 'fertilizer', 'pest_control', 'harvest'] },
        title: { bsonType: 'string' },
        content: { bsonType: 'string' },
        weather_data: { bsonType: 'object' },
        soil_data: { bsonType: 'object' },
        confidence_score: { bsonType: 'double' },
        is_applied: { bsonType: 'bool' },
        applied_date: { bsonType: 'date' },
        created_at: { bsonType: 'date' }
      }
    }
  }
});

// AI种植建议集合索引
db.ai_planting_advice.createIndex({ farmer_id: 1 });
db.ai_planting_advice.createIndex({ crop_type: 1 });
db.ai_planting_advice.createIndex({ advice_type: 1 });
db.ai_planting_advice.createIndex({ is_applied: 1 });
db.ai_planting_advice.createIndex({ created_at: -1 });

// 10. 价格预测集合
db.createCollection('price_predictions', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['product_id', 'predicted_price', 'current_price', 'prediction_date'],
      properties: {
        product_id: { bsonType: 'objectId' },
        predicted_price: { bsonType: 'double' },
        current_price: { bsonType: 'double' },
        prediction_date: { bsonType: 'date' },
        confidence_level: { bsonType: 'double' },
        factors: { bsonType: 'object' },
        created_at: { bsonType: 'date' }
      }
    }
  }
});

// 价格预测集合索引
db.price_predictions.createIndex({ product_id: 1 });
db.price_predictions.createIndex({ prediction_date: 1 });
db.price_predictions.createIndex({ created_at: -1 });

// 11. 知识库集合
db.createCollection('knowledge_base', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['title', 'content'],
      properties: {
        title: { bsonType: 'string' },
        content: { bsonType: 'string' },
        category: { bsonType: 'string' },
        tags: { bsonType: 'array' },
        author: { bsonType: 'string' },
        view_count: { bsonType: 'int' },
        is_featured: { bsonType: 'bool' },
        status: { enum: ['draft', 'published', 'archived'] },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 知识库集合索引
db.knowledge_base.createIndex({ category: 1 });
db.knowledge_base.createIndex({ status: 1 });
db.knowledge_base.createIndex({ is_featured: 1 });
db.knowledge_base.createIndex({ title: 'text', content: 'text' });
db.knowledge_base.createIndex({ created_at: -1 });

// 12. 系统配置集合
db.createCollection('system_configs', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['config_key'],
      properties: {
        config_key: { bsonType: 'string' },
        config_value: { bsonType: 'string' },
        description: { bsonType: 'string' },
        created_at: { bsonType: 'date' },
        updated_at: { bsonType: 'date' }
      }
    }
  }
});

// 系统配置集合索引
db.system_configs.createIndex({ config_key: 1 }, { unique: true });

print('集合和索引创建完成！');

// 插入初始数据
print('开始插入初始数据...');

// 插入商品分类
db.categories.insertMany([
  {
    name: '蔬菜',
    description: '新鲜蔬菜',
    sort_order: 1,
    is_active: true,
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    name: '水果',
    description: '时令水果',
    sort_order: 2,
    is_active: true,
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    name: '粮食',
    description: '优质粮食',
    sort_order: 3,
    is_active: true,
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    name: '肉类',
    description: '新鲜肉类',
    sort_order: 4,
    is_active: true,
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    name: '水产',
    description: '鲜活水产',
    sort_order: 5,
    is_active: true,
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    name: '干货',
    description: '农副产品',
    sort_order: 6,
    is_active: true,
    created_at: new Date(),
    updated_at: new Date()
  }
]);

// 插入系统配置
db.system_configs.insertMany([
  {
    config_key: 'site_name',
    config_value: 'AI助农平台',
    description: '网站名称',
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    config_key: 'site_description',
    config_value: 'AI技术赋能农业，助力农民增收',
    description: '网站描述',
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    config_key: 'contact_email',
    config_value: 'support@zhunong.ai',
    description: '联系邮箱',
    created_at: new Date(),
    updated_at: new Date()
  },
  {
    config_key: 'contact_phone',
    config_value: '400-123-4567',
    description: '联系电话',
    created_at: new Date(),
    updated_at: new Date()
  }
]);

print('初始数据插入完成！');
print('MongoDB初始化完成！'); 